﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sustainalytics.LongRunningTaskManager.Interface;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Configuration;
using Sustainalytics.LongRunningTaskManager;
using System.Net.Http.Formatting;
using System.Net.Http;
using System.Net.Http.Headers;
using Sustainalytics.Utils.Serilog;
using Sustainalytics.Utils.Logging.Serilog.Messages;
using Sustainalytics.Utils.Logging.Serilog;
using Sustainalytics.Utils.Configuration;

namespace Sustainalytics.Governance.Tasks.Tasks
{
    class GovernanceReportsDownloadTask : ILongRunningTask
    {
        public LongRunningTaskTypeEnum Type => LongRunningTaskTypeEnum.GovernancePDFS3;
        private static string _bucketName;
        //private static string _prefix;

        public object Start(LongRunningTaskContext context)
        {
            return GetFileResult(context);
        }

        private ILongRunningTaskResult GetFileResult(LongRunningTaskContext context)
        {
            return TryGetReportFromS3(context);
        }

        private LongRunningTaskS3FileResult TryGetReportFromS3(LongRunningTaskContext context)
        {
            _bucketName = SettingsHelper.Read("s3-governance-reports", "dev-globalaccess-europe/GovernanceReports");
            //_prefix = SettingsHelper.Read("s3prefix-governance-reports", "Dev");
            var param = JsonConvert.DeserializeObject<FileExportS3Dto>(context.ParamJson);
            
            var governancePdfType = param.GovernancePdfType;
            var companyId = param.CompanyId;
            var fileId = param.FileId;
            _bucketName += $"/{governancePdfType}";
            var fileName = governancePdfType == Entities.Governance.GovernancePdfType.Insight ? $"{companyId}_{fileId}.pdf" : $"{companyId}.pdf";
            var fileHandler = new S3FileHandler(fileName, _bucketName);
            var result = fileHandler.ReadFile();

            context.TaskStatus.Progress = 100;

            return new LongRunningTaskS3FileResult
            {
                MimeType = "application/pdf",
                Bucket = result.S3Bucket,
                FileName = context.Title,
                Key = result.S3Key
            };
        }

        private static void SetErrorToContext(LongRunningTaskContext context)
        {
            context.Title = "Failed to get the Company Report for specified company";
            context.TaskStatus.AddError(new LongRunningTaskError
            {
                ErrorCode = 7001,
                Arguments = new List<string> { "Failed to get the Company Report for specified company" }
            });
        }
    }
}
